package user

import (
	"crypto/md5"
	"errors"
	"fmt"
	"gq_volunteer_platform/model"
	"io"
	"strconv"
	"time"

	"github.com/gin-gonic/gin"
	"gorm.io/gorm"
)

type User struct {
	ID             uint `gorm:"primarykey;->"`
	OrganizationId uint
	Name           string
	ProfilePhoto   string
	Openid         string `json:"-"`
	LastIp         string
	LastLoginTime  string
	Token          string

	RealName     string
	IdcardType   string
	Idcard       string
	MobileNumber string
	Sex          string
	Email        string
	Ethnicity    string
	// Qq           string
	// Weibo        string

	// HealthStatus          string
	PoliticalStatus string
	EducationLevel  string
	// ForeignLanguage  string
	EmploymentStatus string
	LivingAddress    string
	// DetailedAddress       string
	// AffiliatedUnit        string
	AffiliatedUnitAddress string

	// ServicePreference string
	// ServiceTarget     string
	// ServiceTime       string
	// ServiceArea       string
	// ServiceDomain     string

	CheckStatus string
	CheckNote   string

	ChangeOrganizationId uint
	ChangeStatus         string
	ChangeNote           string

	Point     int
	ServeHour int

	AllowNotice string

	YearMonth string
	model.BaseTime
	DeletedAt gorm.DeletedAt
}

// 生成 token 处理
func (a *User) NewToken() error {

	var str = strconv.Itoa(int(a.ID)) + time.Now().Format(time.DateTime)

	if s, err := Md5(str); err != nil {
		return err
	} else {
		a.Token = s
	}

	return nil
}

// 密码转为Md5处理
func Md5(s string) (string, error) {
	h := md5.New()
	if _, err := io.WriteString(h, s); err != nil {
		return "", err
	}

	return fmt.Sprintf("%x", h.Sum(nil)), nil
}

// gin.Context get user
func (one *User) Get(c *gin.Context) error {

	if a, exists := c.Get("user"); !exists {
		return errors.New("ctx不存在该用户")
	} else {
		if u, b := a.(User); !b {
			return errors.New("断言error")
		} else {
			*one = u
		}
	}

	return nil
}
